`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    21:44:29 03/31/2014 
// Design Name: 
// Module Name:    debouncer 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module debouncer(i_button, i_clk, o_button);
	input i_button;
	input i_clk;
	output reg o_button;	//output value is 0 or 1
	reg [1:0] state, next_state;
	reg [30:0] count;                     //wait period before we accept next input
  
  always@(posedge i_clk) begin  
		state <= next_state;
	end
	
	always @ (posedge i_clk) begin		//state 0 is output 0, idle
      case(state)						//state 1 is output 1, count=0
          2'b00: begin					//state 2 is ouput 0, count=count+1
              if (i_button==1)
                  next_state <= 1;
              else
                  next_state <= 0;
              end
          2'b01: begin
                  next_state <= 2;
              end
          2'b10: begin
              if(count >= 31'd100000)
                  next_state <= 0;
              else
                  next_state <= 2;
              end
          default: next_state <= 0;
		endcase
	end
	
	always @ (posedge i_clk) begin
		case (state)
			0: begin
				o_button <= 0;
				count <= 0;
			end
			
			1: begin
				o_button <= 1;
				count <= 0;
			end
			
			2: begin
				o_button <= 0;
				count <= count + 1'b1;
			end
			
			default: begin 
				o_button <= 0;
				count <= 0;
			end
		endcase
	end
endmodule
